package com.andy.blog.quartz.task;

import com.andy.blog.common.constant.CacheConstants;
import com.andy.blog.common.core.redis.RedisCache;
import com.andy.blog.common.enums.DeleteTypeEnum;
import com.andy.blog.dal.domain.ArticleDO;
import com.andy.blog.dal.service.ArticleDalService;
import com.andy.blog.dal.vo.ArticleVO;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * Created by andy on 2023/11/19 13:07
 */
@Component("articleTask")
public class ArticleTask {

    private static final Logger logger = LoggerFactory.getLogger(ArticleTask.class);

    @Autowired
    private RedisCache redisCache;

    @Resource
    private ArticleDalService articleDalService;

    /**
     * 同步文章浏览量
     * 0 0 0 * * ?
     */
    public void syncViewCount() {

        logger.info("articleTask.syncViewCount.start...");
        List<ArticleDO> articleDOList = articleDalService.selectList(ArticleVO.builder().isDeleted(DeleteTypeEnum.DELETE_N.getCode()).build());

        if (CollectionUtils.isNotEmpty(articleDOList)) {
            for (ArticleDO articleDO : articleDOList) {
                Double zsetScore = redisCache.getZsetScore(CacheConstants.ARTICLE_VIEW_COUNT, articleDO.getId());
                Long articleViewCount = Optional.ofNullable(zsetScore).map(Double::longValue).orElse(null);
                logger.info("articleId:: [{}]; articleViewCount:: [{}]", articleDO.getId(), articleViewCount);
                if (Objects.nonNull(articleViewCount)) {
                    ArticleDO article = new ArticleDO();
                    article.setId(articleDO.getId());
                    article.setArticleViewCount(articleViewCount);
                    articleDalService.updateById(article);
                }
            }
        }
        logger.info("articleTask.syncViewCount.end...");
    }

    /**
     * 同步文章浏览量
     * 0 0 1 * * ?
     */
    public void syncLikeCount() {

        logger.info("articleTask.syncLikeCount.start...");
        List<ArticleDO> articleDOList = articleDalService.selectList(ArticleVO.builder().isDeleted(DeleteTypeEnum.DELETE_N.getCode()).build());
        if (CollectionUtils.isNotEmpty(articleDOList)) {
            for (ArticleDO articleDO : articleDOList) {
                Integer likeCount = redisCache.getHash(CacheConstants.ARTICLE_LIKE_COUNT, articleDO.getId() + "");

                ArticleDO article = new ArticleDO();
                article.setId(articleDO.getId());
                article.setArticleLikeCount(likeCount);
                articleDalService.updateById(article);
            }
        }

    }
}
